206.Course Schedule.cpp #151
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🧩 LeetCode 207 — Course Schedule
🧠 Intuition
The problem is about determining if all courses can be completed given their prerequisites.
Think of each course as a node in a directed graph, and each prerequisite pair
[a, b]as a directed edge fromb → a— meaningbmust be completed beforea.If there’s a cycle, it means a course depends on itself (directly or indirectly), so it’s impossible to complete all courses.
Hence, the task reduces to detecting if the directed graph has a cycle.
🚀 Approach
We use Kahn’s Algorithm (Topological Sorting using BFS) to determine if all nodes can be visited without a cycle.
Build the Graph
adjfor the courses.inDegreearray to store how many prerequisites each course has.Initialize Queue
inDegree == 0(no prerequisites) into a queue.Process Courses
xfrom the queue and increment acountof completed courses.adj[x], decrement itsinDegree.inDegreebecomes0, push it into the queue.Check for Cycles
count == V(all courses processed), returntrue.false.💻 Code Solution (C++)
✅ By submitting this PR, I confirm that: